﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Globalization;


namespace BLL
{
    public class Http
    {
        public Http()
        {
        }
        /// <summary>
        /// 检查用户名、密码是否匹配
        /// </summary>
        /// <returns>注意，当两者不匹配时返回true匹配时返回false</returns>
        public bool CheckInfo(string strName, string strPassword, string strCookie)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "userName=" + strName;
            postData += ("&password=" + strPassword);
            byte[] data = encoding.GetBytes(postData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://portal.tsinghua.edu.cn/Login");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            CookieContainer co = new CookieContainer();
            co.SetCookies(new Uri("http://portal.tsinghua.edu.cn/"), strCookie);
            request.CookieContainer = co;
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            return content.Contains("loginError");
        }
        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="strURL"></param>
        /// <returns></returns>
        public string GetCookie(string strURL)
        {
            try
            {
                HttpWebRequest httpWebRequest;
                HttpWebResponse webResponse;
                httpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
                httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.Accept =
                    "text/html, application/xhtml+xml, */*";
                httpWebRequest.UserAgent =
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
                httpWebRequest.Method = "Get";
                webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                string[] strSep = new string[] { ";" };
                return webResponse.Headers.Get("Set-Cookie").Split(strSep, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            catch
            {
                return null;
            }

        }
        public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header)
        {
            long contentLength;
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;
            Stream getStream;

            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
            CookieContainer co = new CookieContainer();
            co.SetCookies(new Uri(server), cookie);

            httpWebRequest.CookieContainer = co;

            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept =
                "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            httpWebRequest.Referer = "http://portal.tsinghua.edu.cn/index.jsp";
            httpWebRequest.UserAgent =
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            httpWebRequest.Method = "Post";
            httpWebRequest.ContentLength = byteRequest.Length;
            Stream stream;
            stream = httpWebRequest.GetRequestStream();
            stream.Write(byteRequest, 0, byteRequest.Length);
            stream.Close();
            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            header = webResponse.Headers.ToString();
            getStream = webResponse.GetResponseStream();
            contentLength = webResponse.ContentLength;

            byte[] outBytes = new byte[contentLength];
            outBytes = ReadFully(getStream);
            getStream.Close();
            return outBytes;
        }
        public static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[128];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
        public static string GetHtml(string URL, string cookie, out string header, string server)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;
            Stream getStream;
            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
            if (cookie != null)
            {
                CookieContainer co = new CookieContainer();
                co.SetCookies(new Uri(server), cookie);
                httpWebRequest.CookieContainer = co;
            }
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept =
                "text/html, application/xhtml+xml,*/*";
            httpWebRequest.UserAgent =
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            httpWebRequest.Method = "Get";

            try
            {
                webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                getStream = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(getStream, Encoding.Default);
                string getString = reader.ReadToEnd();
                header = webResponse.Headers.Get("Set-Cookie");
                reader.Close();
                getStream.Close();
                return getString;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public string GetTicket(string URL, string cookie, out string header, string server)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;
            Stream getStream;
            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
            httpWebRequest.AllowAutoRedirect = false;
            if (cookie != null)
            {
                CookieContainer co = new CookieContainer();
                co.SetCookies(new Uri(server), cookie);
                httpWebRequest.CookieContainer = co;
            }
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept =
                "text/html, application/xhtml+xml,*/*";
            httpWebRequest.UserAgent =
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            httpWebRequest.Method = "Get";

            try
            {
                webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                getStream = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(getStream, Encoding.Default);
                string getString = reader.ReadToEnd();
                header = webResponse.Headers.Get("Set-Cookie");
                reader.Close();
                getStream.Close();
                return getString.Split(new string[] { "\"" }, StringSplitOptions.RemoveEmptyEntries)[1];
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取助学金查询结果
        /// </summary>
        /// <param name="strCookie"></param>
        public void GetGrantsData(string strCookie)
        {
            string strHeader;
            string strRoam = GetHtml("http://portal.tsinghua.edu.cn/minichan/roamaction.jsp?id=2503", strCookie, out strHeader, "http://portal.tsinghua.edu.cn");
            if (strRoam.Contains("转接中，请稍候"))
            {
                strCookie = strHeader.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)[0];
                string strQuery = "user=2008010814&nianyue=201101";
                string strData = PostHtml("http://166.111.14.8:8081/zxjcx/display.jsp", strCookie, out strHeader, "http://166.111.14.8:8081", strQuery);
            }
        }
        /// <summary>
        /// 获取银行代发数据
        /// </summary>
        ///<remark>
        ///这个网站很有意思，似乎可以直接接受info的Cookie？等有时间再研究吧
        ///</remark>
        public string GetBankData(string strCookie, string strQuery)
        {
            string strHeader;
            string s;
            string strRoam = GetTicket("http://portal.tsinghua.edu.cn/minichan/roamaction.jsp?id=68", strCookie, out strHeader, "http://portal.tsinghua.edu.cn");
            //strCookie = strHeader.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)[0];
            GetHtml(strRoam, strCookie, out s, "http://166.111.14.8");
            string strData = PostHtml("http://166.111.14.8:8080/info/search.do", strCookie, out strHeader, "http://166.111.14.8", strQuery);
            return strData;
        }
        public string PostHtml(string strURL, string strCookie, out string strHeader, string strServer, string strPostData)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;
            Stream getStream;
            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(strURL);
            CookieContainer co = new CookieContainer();
            co.SetCookies(new Uri(strServer), strCookie);
            httpWebRequest.CookieContainer = co;
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept =
                "text/html, application/xhtml+xml, */*";
            httpWebRequest.UserAgent =
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            httpWebRequest.Method = "Post";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(strPostData);
            httpWebRequest.ContentLength = data.Length;
            Stream newStream = httpWebRequest.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            getStream = webResponse.GetResponseStream();
            StreamReader reader;
            if (strServer == "http://ecard.tsinghua.edu.cn")
                reader = new StreamReader(getStream, Encoding.UTF8);
            else
                reader = new StreamReader(getStream, Encoding.Default);
            string getString = reader.ReadToEnd();
            strHeader = webResponse.Headers.Get("Set-Cookie");
            reader.Close();
            getStream.Close();
            if (webResponse != null)
                webResponse.Close();
            if (httpWebRequest != null)
                httpWebRequest.Abort();
            return getString;

        }
        public string GetRecognition(PictureBox pb)
        {
            try
            {
                string strURL = "http://ecard.tsinghua.edu.cn/user/Index.do";
                string strHeader;
                GetHtml(strURL, null, out strHeader, "http://ecard.tsinghua.edu.cn/");
                string[] strCookie = strHeader.Split(new string[] { "; path=/", "," }, StringSplitOptions.RemoveEmptyEntries);
                HttpWebRequest httpWebRequest;
                HttpWebResponse webResponse;
                Stream getStream;
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://ecard.tsinghua.edu.cn/RandImage");
                CookieContainer co = new CookieContainer();
                Uri uri = new Uri("http://ecard.tsinghua.edu.cn/");
                co.SetCookies(uri, strCookie[0] + "," + strCookie[1]);
                httpWebRequest.CookieContainer = co;
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.Accept =
                    "image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5";
                httpWebRequest.UserAgent =
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
                httpWebRequest.Method = "Get";
                webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                getStream = webResponse.GetResponseStream();
                pb.Image = Image.FromStream(getStream).Clone() as Image;
                getStream.Close();
                return strCookie[0] + "," + strCookie[1];
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

        }
        public bool CheckECard(string strName, string strPassword, string strVertification, string strCookie)
        {
            string strHeader;
            string strPostData = "name=" + strName + "&password=" + strPassword + "&verificationcode=" + strVertification + "&logintype=1";
            try
            {
                string strLogin = PostHtml("http://ecard.tsinghua.edu.cn/user/Login.do", strCookie, out strHeader, "http://ecard.tsinghua.edu.cn", strPostData);
                if (strLogin.Contains("UserIndex.do"))
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }

        }
        public string GetECardData(string strCookie, string strQuery)
        {
            string strHeader;

            string strData = PostHtml("http://ecard.tsinghua.edu.cn/user/UserExDetails.do", strCookie, out strHeader, "http://ecard.tsinghua.edu.cn", strQuery);
            return strData;
        }
        /// <summary>
        /// 析取网页数据
        /// </summary>
        /// <param name="strData">网页数据组成的字符串</param>
        /// <param name="bContinue">指示是否继续获取下一页</param>
        /// <returns></returns>
        public RecordCollection AnalyzeECardData(string strData, out bool bContinue)
        {
            ///获取Record属性相关项
            string strRegex = @"<div align=""center"">(?<g1>\d+?)</div>[\s\S]*?class=""font10-black"">(?<g2>\S+?)</div>[\s\S]*?class=""font10-black"">(?<g3>\S+?)</div>[\s\S]*?class=\""font10-black\"">(?<g4>\d+?)</div>[\s\S]*?center\"">(?<g5>\S+?)</div>[\s\S]*?￥(?<g6>\d+\.\d+)</div>";
            Regex r = new Regex(strRegex);
            MatchCollection mc = r.Matches(strData);
            Record rd;
            RecordCollection rdc = new RecordCollection();

            ///获取页面的记录条数
            Regex rx = new Regex(@"共(\d+?)条记录");
            Match m = rx.Match(strData);
            if (mc.Count == 0)
            {
                bContinue = false;
                return rdc;
            }
            for (int i = 0; i < mc.Count; i++)
            {
                rd = new Record();
                rd.AccountID = 1;
                if (mc[i].Groups[3].Value == "消费")
                {
                    switch (mc[i].Groups[2].Value)
                    {
                        case "饮食中心":
                            rd.TypeID = 1;
                            rd.Remark = MatchCanteenID(mc[i].Groups[4].Value);
                            break;
                        case "紫荆服务楼超市":
                            rd.TypeID = 5;
                            break;
                        default:
                            rd.TypeID = 6;
                            break;
                    }
                }
                else if (mc[i].Groups[3].Value == "领取圈存")
                    rd.TypeID = 3;
                else if (mc[i].Groups[3].Value == "自助缴费")
                    rd.TypeID = 9;
                else if (mc[i].Groups[3].Value == "领取旧卡余额")
                {
                    rdc.Remove(rd);
                    continue;
                }
                else
                    rd.TypeID = 10;
                rd.Time = DateTime.Parse(mc[i].Groups[5].Value);
                rd.Amount = Double.Parse(mc[i].Groups[6].Value);
                rdc.Add(rd);

            }
            if (mc[mc.Count - 1].Groups[1].Value == m.Groups[1].Value)
                bContinue = false;
            else
                bContinue = true;
            return rdc;



        }
        public RecordCollection AnanlyzeBankData(string strData)
        {
            string strRex = @"<tr>\r\n    <td><font size=""2"">(?<g1>\d+?)</font>[\s\S]*?;(?<g2>[\s\S]+?)</font>[\s\S]*?;(?<g3>[\s\S]+?)</font>[\s\S]*?""2"">(?<g4>\S+?)</font>[\s\S]*?中国银行[\s\S]*?size=""2"">(?<g5>[\S\s]+?)</font>[\s\S]*?color=""blue"">(?<g6>\S+?)\r\n";
            Regex r = new Regex(strRex);
            MatchCollection mc = r.Matches(strData);
            Record rd;
            RecordCollection rdc = new RecordCollection();
            for (int i = 0; i < mc.Count; i++)
            {
                rd = new Record();
                rd.AccountID = 2;
                rd.TypeID = 4;
                rd.Remark = mc[i].Groups[4].Value;
                DateTime dt = new DateTime();
                DateTime.TryParseExact(mc[i].Groups[5].Value, "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
                rd.Time = dt;
                rd.Amount = Double.Parse(mc[i].Groups[6].Value);
                rdc.Add(rd);
            }
            return rdc;
        }
        public string MatchCanteenID(string strID)
        {
            int i = Convert.ToInt32(strID);
            if (i <= 20000900 && i >= 20000788)
                return "紫荆园";
            else if (i <= 20000750 && i >= 20000500)
                return "桃李园";
            else if (i >= 20001000 && i <= 20001100)
                return "观畴园";
            else if (i >= 20001550 && i <= 20001600)
                return "闻馨园";
            else if (i >= 20001300 && i <= 20001350)
                return "听涛园";
            else return "其他食堂";
        }

    }
}
